package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.EmailPackage;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.service.AuthService;
import com.shlh.saas.service.EmailPackageService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 邮件套餐控制器
 */
@RestController
@RequestMapping("/email")
public class EmailPackageController {

    private static final Logger log = LoggerFactory.getLogger(EmailPackageController.class);

    @Autowired
    private EmailPackageService emailPackageService;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取所有邮件套餐列表
     * @return 套餐列表
     */
    @GetMapping("/packages")
    public Result<List<EmailPackage>> getEmailPackages() {
        log.info("接收到获取邮件套餐列表的请求");
        try {
            List<EmailPackage> packages = emailPackageService.getAllValidPackages();
            log.info("成功返回邮件套餐列表，共{}个套餐", packages != null ? packages.size() : 0);
            return Result.success(packages);
        } catch (Exception e) {
            log.error("获取邮件套餐列表时发生异常: {}", e.getMessage(), e);
            return Result.error("获取邮件套餐列表失败，请稍后重试");
        }
    }
    
    /**
     * 获取用户的邮件剩余次数
     * @return 用户邮件剩余次数
     * @deprecated 使用EmailController中的/email/quota接口代替
     */
    @GetMapping("/package/quota")
    public Result<Map<String, Object>> getEmailPackageQuota() {
        try {
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            String phone = user.getPhone();
            UserBalance userBalance = userBalanceService.getUserBalance(phone);
            
            Map<String, Object> data = new HashMap<>();
            if (userBalance != null) {
                data.put("emailSendRemaining", userBalance.getEmailSendRemaining());
            } else {
                data.put("emailSendRemaining", 0);
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户邮件剩余次数时发生异常: {}", e.getMessage(), e);
            return Result.error("获取邮件剩余次数失败，请稍后重试");
        }
    }
    
    /**
     * 购买邮件套餐
     * @param packageId 套餐ID
     * @return 购买结果
     */
    @PostMapping("/purchase")
    public Result<Boolean> purchaseEmailPackage(@RequestParam Long packageId) {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.error("获取用户ID失败，用户未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                log.error("用户ID({})不存在", userId);
                return Result.error("用户不存在");
            }
            
            String phone = user.getPhone();
            
            log.info("接收到当前登录用户购买邮件套餐请求，用户ID: {}, 手机号: {}, 套餐ID: {}", userId, phone, packageId);
            
            boolean success = emailPackageService.purchaseEmailPackage(phone, packageId);
            log.info("用户{}(ID:{})购买ID为{}的邮件套餐结果: {}", phone, userId, packageId, success ? "成功" : "失败");
            
            if (success) {
                return Result.success(true, "购买成功");
            } else {
                return Result.error("购买失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("购买邮件套餐时发生异常: {}", e.getMessage(), e);
            return Result.error("购买过程中发生错误，请稍后重试");
        }
    }
    
    /**
     * 获取邮件发送记录
     * @param page 页码
     * @param size 每页大小
     * @return 邮件发送记录列表
     * @deprecated 使用EmailController中的/email/send-records接口代替
     */
    @GetMapping("/package/send-records")
    public Result<Map<String, Object>> getEmailPackageSendRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 获取发送记录
            String phone = user.getPhone();
            Map<String, Object> records = emailPackageService.getEmailSendRecords(phone, page, size);
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取邮件发送记录时发生异常: {}", e.getMessage(), e);
            return Result.error("获取邮件发送记录失败，请稍后重试");
        }
    }
} 